#!/bin/sh

case "$1" in
    "stop")
        # Stop AList server
        if ps | grep "[a]list server"; then
            kill $(ps | grep "[a]list server" | awk '{print $1}') 2>/dev/null
            echo "AList has stopped."
        else
            echo "AList is not running."
        fi
        ;;
    "disable")
        # Disable AList server autorun
        cd /data/auto_run
        sed -i 's/"")$/"auto_run")/g' /data/auto_run/20_start_alist.sh
        export PATH=$(echo "$PATH" | sed 's|:/data/other/alist||g; s|/data/other/alist:||g; s|/data/other/alist||g')
        uci delete firewall.$(uci show firewall | awk -F'[.=]' '/Allow AList/ {print $2; exit}')
        uci commit firewall
        /etc/init.d/firewall restart
        ;;
    "start")
        cd /data/other/alist/
        # Start the alist server in the background
        /data/other/alist/alist server &
        ;;
    "enable")
        cd /data/auto_run
        sed -i 's/"auto_run")$/"")/g' /data/auto_run/20_start_alist.sh
        /data/auto_run/20_start_alist.sh
        ;;
    "")
        cd /data/other/alist/
        # Check if /data/other/alist is in the PATH environment variable
        export PATH="$PATH:/data/other/alist"
        # Check if the firewall has a rule for port 5244
        if ! uci show firewall | grep "alist"; then
            # Add a rule to allow access to port 5244 from any interface
            uci add firewall rule
            uci set firewall.@rule[-1].name='Allow AList'
            uci set firewall.@rule[-1].src='*'
            uci set firewall.@rule[-1].proto='tcp'
            uci set firewall.@rule[-1].dest_port='5244'
            uci set firewall.@rule[-1].target='ACCEPT'
            uci commit firewall
            /etc/init.d/firewall restart
        fi
        # Start the alist server in the background
        /data/other/alist/alist server &
        ;;
    *)
        echo "usage: $0 [start|stop|enable|disable]"
        exit 1
        ;;
esac